package com.xa8bit.service.impl;

import com.xa8bit.dao.IUserDao;
import com.xa8bit.domain.User;
import com.xa8bit.service.IUserService;
import com.xa8bit.util.PasswordUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Objects;

/**
 * @author lingwh
 * @desc
 * @date 2025/7/10 17:27
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    @Override
    public boolean login(User user) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //创建查询条件数据对象
        User condition = new User();
        condition.setUsername(user.getUsername());

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.exact()) // 姓名采用“全文匹配”的方式查询
                .withIgnorePaths("focus");  //忽略属性：是否关注。因为是基本类型，需要忽略掉

        //创建实例
        Example<User> example = Example.of(condition, matcher);

        User userFromDb = userDao.findOne(example).get();
        if(Objects.nonNull(userFromDb)) {
            String salt = userFromDb.getSalt();
            return PasswordUtils.verify(user.getPassword(), salt, userFromDb.getPassword());
        }
        return false;
    }

}
